package com.example.demo.interceptor;

import com.example.demo.mapper.UserMapper;
import com.example.demo.utils.JwtUtil;
import com.example.demo.utils.SpringContext;
import com.example.demo.utils.UserUtil;
import jakarta.annotation.Resource;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class AuthHandShakeInterceptor implements HandshakeInterceptor {

    @Resource
    private UserUtil util;

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        String query = request.getURI().getQuery();
        if (query == null) return false;
        Map<String, String> queryParams = parseQueryParams(query);
        String token = null;
        String receiveUsername = null;
        try {
            token = queryParams.get("token");
            receiveUsername = queryParams.get("to");
        } catch (Exception e) {
            throw new RuntimeException("token或receiveUsername为空", e);
        }

        if (token != null) {
            String username = new JwtUtil().extractUsername(token);
            int userId = util.getUserId(username);
            attributes.put("userId", userId);
            attributes.put("username", username);
            if (receiveUsername != null){
                attributes.put("receiveUsername", receiveUsername);
                attributes.put("receiveUserId", SpringContext.getBean(UserMapper.class).getUserByUsername(receiveUsername).getUserId());
            }
            return true;
        }
        return false;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {

    }



    private Map<String, String> parseQueryParams(String query) {
        return Arrays.stream(query.split("&"))
                .map(param -> param.split("="))
                .collect(Collectors.toMap(
                        pair -> URLDecoder.decode(pair[0], StandardCharsets.UTF_8),
                        pair -> URLDecoder.decode(pair[1], StandardCharsets.UTF_8)
                ));
    }
}
